﻿using KingerRobot.PCRBW.Dao;
using KingerRobot.PCRBW.Spi;
using KingerRobot.PCRBW.SpiService.Helpers;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace KingerRobot.PCRBW.SpiService;

public class WarehousImpl : IWarehousService
{
    private readonly static ITaskService _taskService =new WcsTaskImpl();
    private readonly static IMesProductRepositories _mesProductRepositories = new MesProductRepositories();
    private readonly static IMesOutOrdersRepositories _mesOutOrdersRepositories = new MesOutOrdersRepositories();
    private readonly static IWmsSettingRepositories _wmsSettingRepositories = new WmsSettingRepositories();

    #region 创建任务

    /// <summary>
    /// 创建入库任务
    /// </summary>
    public int CreateWarehouseingTask(long equip_id,string slidtable)
    {
        return _taskService.CreateWarehouseing(equip_id, (int)EnumExecStatus.SlideComplete, slidtable);
    }
    /// <summary>
    /// 创建出库任务
    /// </summary>
    public int CreateExWarehouseTask(long equip_id)
    {
        return _taskService.CreateExWarehouse(equip_id, (int)EnumExecStatus.Add);
    }
    #endregion

    #region 任务执行
    /// <summary>
    /// 任务执行
    /// </summary>
    /// <param name="locId">库位</param>
    /// <param name="taskId">任务号</param>
    /// <returns>-1未查询到任务 1任务更改成功；0 当前任务没有是创建的</returns>
    public int ExecuteTask(long locId, int taskNo)
    {
        // 更新任务指令状态
        int result = _taskService.UpdateTaskAndCmdStatus(locId, taskNo, (int)EnumTaskCmdStatus.Executed);
        if (result > 0)
        {
            return 1;
        }
        return -1;
    }

    #endregion

    #region 任务完成
    /// <summary>
    /// 任务完成
    /// </summary>
    /// <param name="taskNo"></param>
    /// <returns></returns>
    public int FinishTask(int taskNo)
    {
        try
        {
            Expression<Func<POWcsTask, bool>> whereExpression = x => true;
            whereExpression = whereExpression.And(d=>d.TaskNo== taskNo && d.UseFlag==1 && d.TaskStatus==(int)EnumTaskStatus.Executed);
            var task = _taskService.QueryFrist(whereExpression);
            if (task is null || task.Task == null || task.Cmd == null)
            {
                WriteLog($"未查询到任务，任务号:[{taskNo}]",true);
                return 0;
            }
           
            //更新产品信息状态、订单状态
            UpdateTaskStatus(task);
           
            return 1;
        }
        catch (Exception ex)
        {
            WriteLog($"更新数据异常!{ex.Message}", true);
            return -1;
        }
    }

    private static void UpdateTaskStatus(TaskAndCmdBean task)
    {
        var product = _mesProductRepositories.QueryById(task.Task.MesId);
        if (task.Task.TaskType == (int)EnumTaskType.Warehousing)
        {
            MesProduct mesProduct = new MesProduct();
            mesProduct.Id = task.Task.MesId;
            mesProduct.Status = (int)EnumProductStatus.TheWarehouse;
            mesProduct.BatchName= product.BatchName;
            mesProduct.innerdiameter = product.innerdiameter;

            PORcsLocation rcsLocation = new PORcsLocation();
            rcsLocation.Id = task.Task.TargetLoc;
            rcsLocation.TaskId = null;
            rcsLocation.TaskOccupyTime = null;
            rcsLocation.TaskOccupy = 0;
            rcsLocation.LocHasSku = 1;
            rcsLocation.LocHasSkuTime = DateTime.Now;
            rcsLocation.MaterialId = product.PartNumber;
            rcsLocation.ProductBatch = product.BatchName;
            rcsLocation.TaskOccupyTime = null;
            rcsLocation.UpdateTime = DateTime.Now;
            rcsLocation.MdTime = product.ProduceTime;
            rcsLocation.SkuRealCount = Decimal.Parse(product.Quantity.ToString());
            rcsLocation.LocSize =Decimal.Parse(product.innerdiameter.ToString());
            rcsLocation.Pid = task.Task.MesId;

            // 修改任务状态
            _mesProductRepositories.ExecUpdateStatusTran(mesProduct, rcsLocation);
            _taskService.UpdateTaskAndCmdStatus(task.Task.TargetLoc.GetValueOrDefault(), task.Task.TaskNo.GetValueOrDefault(), (int)EnumTaskStatus.Finish);
            return;
        }
        if (task.Task.TaskType == (int)EnumTaskType.Exwarehouse)
        {
            MesOutOrder mesOutOrder = new MesOutOrder();
            MesProduct mesProduct = new MesProduct();
            mesProduct.Id = task.Task.MesId;
            mesProduct.Status = (int)EnumExecStatus.ExeWarehouseComplete;
            //出库
            if (task.Task.Mark == 0)
            {
                mesOutOrder.Id = task.Task.OrderId.ToString();
                mesOutOrder.Status = (int)EnumMesOutOrder.ExWarehouseCompleted;
                mesOutOrder.TargetLoc = task.Task.TargetLoc;
            }
            //人工出库
            if (task.Task.Mark == 2)
            {
                mesOutOrder.Id = task.Task.OrderId.ToString();
                mesOutOrder.Status = (int)EnumMesOutOrder.AbnormalCompleted;
                mesOutOrder.TargetLoc = task.Task.TargetLoc;
            }
            PORcsLocation rcsLocation = new PORcsLocation();
            rcsLocation.Id = task.Task.StartLoc;
            rcsLocation.TaskId = null;
            rcsLocation.TaskOccupy = 0;
            rcsLocation.TaskOccupyTime = null;
            rcsLocation.LocHasSku = 0;
            rcsLocation.SkuRealCount = 0;
            rcsLocation.UpdateTime = DateTime.Now;
            rcsLocation.LocHasSkuTime = null;
            rcsLocation.MaterialId = null;
            rcsLocation.ProductBatch = string.Empty;
            rcsLocation.MdTime = null;
            rcsLocation.Remarks = $"清空货位数据 TaskNO{task.Task.TaskNo}";
            rcsLocation.Pid = task.Task.MesId;
            rcsLocation.LocSize =Decimal.Parse(task.Task.Innerdiameter);
            _mesOutOrdersRepositories.ExecUpdateExWarehousStatusTran(mesOutOrder, rcsLocation, task.Task);
            _taskService.UpdateTaskAndCmdStatus(task.Task.TargetLoc.GetValueOrDefault(), task.Task.TaskNo.GetValueOrDefault(), (int)EnumTaskStatus.Finish);

        }
    }

    #endregion

    #region 获取龙门所有任务
    public List<TaskCmdAndLocDto> GetTaskAndCmdBeanByCmdEquipId(long equipId)
    {
        return _taskService.GetTaskAndCmdBeanByCmdEquipId(equipId);
    }
    #endregion

    #region 获取配置
    public List<WmsSetting> QuerySetting()
    {
        Expression<Func<WmsSetting, bool>> whereExpression = x => true;
        whereExpression = whereExpression.And(d => d.UseFlag ==1);
        return _wmsSettingRepositories.Query(whereExpression);
    }
    #endregion

}
